package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.respVo.BaseResp;
import com.qf.pojo.vo.QfCourse;
import com.qf.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public BaseResp search(String keyword, Integer page, Integer size, String sort) {

//        //1.设置分页
//        PageHelper.startPage(page,size);
//        //2.去数据库查询
//        List<QfCourse> search = qfCourseDao.search("%" + keyword + "%", sort);
//        //3.分成page
//        PageInfo<QfCourse> of = PageInfo.of(search);
        SearchRequest searchRequest = new SearchRequest("qf-course");
        searchRequest.types("doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (keyword.equals("null")){
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            searchSourceBuilder.query(matchAllQueryBuilder);
        }else{
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "courseName", "courseDescription");
            searchSourceBuilder.query(multiMatchQueryBuilder);
        }
        //如果sort不为Null
        if (!sort.equals("null")){
            if (sort.equals("asc")){
                searchSourceBuilder.sort("pay",SortOrder.ASC);
            }else{
                searchSourceBuilder.sort("pay",SortOrder.DESC);
            }
        }
        //设置 分页数据
        Integer from = (page-1)*size;
        searchSourceBuilder.size(size);
        searchSourceBuilder.from(from);
        //高亮的配置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("courseName");
        highlightBuilder.field("courseDescription");
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        //使用client进行远程的搜索
        Long total=null;
        //定义一个集合
        List list = new ArrayList();
        try {
            SearchResponse search = client.search(searchRequest);
            //解析返回值
            SearchHits hits = search.getHits();
             total= hits.getTotalHits();
            //继续解析
            SearchHit[] hits1 = hits.getHits();


            if (hits1!=null&&hits1.length>0){
                for (SearchHit hi:hits1
                     ) {
                    Map<String, Object> sourceAsMap = hi.getSourceAsMap();
                    //解析出高亮字段
                    Map<String, HighlightField> highlightFields = hi.getHighlightFields();
                    //从map中获取到高亮字段
                    HighlightField courseName = highlightFields.get("courseName");
                    HighlightField courseDescription = highlightFields.get("courseDescription");

                    if (courseName!=null){
                        StringBuffer stringBuffer = new StringBuffer();
                        Text[] fragments = courseName.getFragments();
                        if (fragments!=null&&fragments.length>0){
                            for (Text te:fragments
                                 ) {
                                stringBuffer.append(te);
                            }
                            //进行赋值替换
                            sourceAsMap.put("courseName",stringBuffer.toString());
                        }
                    }

                    if (courseDescription!=null){
                        StringBuffer stringBuffer = new StringBuffer();
                        Text[] fragments = courseDescription.getFragments();
                        if (fragments!=null&&fragments.length>0){
                            for (Text te:fragments
                            ) {
                                stringBuffer.append(te);
                            }
                            //进行赋值替换
                            sourceAsMap.put("courseDescription",stringBuffer.toString());
                        }
                    }
                    //将sourceAsMap 转为返回的对象结果集
                    String s = JSONObject.toJSONString(sourceAsMap);
                    QfCourse qfCourse = JSONObject.parseObject(s, QfCourse.class);
                    list.add(qfCourse);
                }
            };
        } catch (IOException e) {
            e.printStackTrace();
            return new BaseResp(0,"搜索失败！",null,null);
        }

        return new BaseResp(1,"查询成功！",list,total);
    }
}
